<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.supplierId ? $t('crud.addTitle') : $t('temp.modify')"
    :close-on-click-modal="false"
    @closed="onClosedDialog"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('shop.supplierName')"
        prop="supplierName"
      >
        <el-input
          v-model="dataForm.supplierName"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        :label="$t('shop.tel')"
        prop="tel"
      >
        <el-input
          v-model="dataForm.tel"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.areaName')"
        prop="province"
      >
        <el-col :span="8">
          <el-form-item prop="province">
            <el-select
              ref="dataSelectRef"
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="city">
            <el-select
              ref="dataSelectRef"
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="area">
            <el-select
              ref="dataSelectRef"
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          maxlength="150"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.contactName')"
        prop="contactName"
      >
        <el-input
          v-model="dataForm.contactName"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.contactTel')"
        prop="contactTel"
      >
        <el-input
          v-model="dataForm.contactTel"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.qq')"
        prop="qqNumber"
      >
        <el-input
          v-model="dataForm.qqNumber"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.weChatNumber')"
        prop="wxNumber"
      >
        <el-input
          v-model="dataForm.wxNumber"
          maxlength="40"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.mailbox')"
        prop="mail"
        :rules="[{ type: 'email', message: $t('sys.emailaError'), trigger: ['blur', 'change'] }]"
      >
        <el-input
          v-model="dataForm.mail"
          maxlength="40"
          show-word-limit
          :validate-event="dataForm.mail!=null"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.fax')"
        prop="fax"
      >
        <el-input
          v-model="dataForm.fax"
          maxlength="40"
          show-word-limit
          oninput="value=value.replace(/\D/g, '')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('product.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">
            {{ $t('groups.startUsing') }}
          </el-radio>
          <el-radio :label="0">
            {{ $t('publics.disable') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="primary-btn default-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { isMobile, isStarMobile, isQq } from '@/utils/validate'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

// 自定义校验函数
// eslint-disable-next-line no-unused-vars
const validateSupplierName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shop.supplierName') + $t('publics.noNull')))
  } else {
    callback()
  }
}
const dataFormRef = ref(null)
// eslint-disable-next-line no-unused-vars
const validPhone = (rule, value, callback) => {
  if (value == null || value === '' || value === ' ') {
    dataFormRef.value.clearValidate('tel')
    callback() // phoneErrorTips
  } else if (dataForm.value.supplierId ? !isStarMobile(value) : !isMobile(value)) {
    callback(new Error($t('shop.phoneErrorTips')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateQq = (rule, value, callback) => {
  if (value == null || value === '' || value === ' ') {
    dataFormRef.value.clearValidate('qqNumber')
    callback() // qqErrorTips
  } else if (!isQq(value)) {
    callback(new Error($t('shop.qqErrorTips')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validMobile = (rule, value, callback) => {
  if (value == null || value === '' || value === ' ') {
    dataFormRef.value.clearValidate('contactTel')
    callback()
  } else if (dataForm.value.supplierId ? !isStarMobile(value) : !isMobile(value)) {
    callback(new Error($t('shop.mobileErrorTips')))
  } else {
    callback()
  }
}
const dataRule = {
  supplierName: [
    { required: true, message: $t('shop.supplierName') + $t('publics.noNull'), trigger: 'blur' },
    { validator: validateSupplierName, trigger: ['blur', 'change'] }
  ],
  tel: [{ validator: validPhone, trigger: ['blur', 'change'] }],
  contactTel: [{ validator: validMobile, trigger: ['blur', 'change'] }],
  qqNumber: [{ validator: validateQq, trigger: ['blur', 'change'] }]
}

const visible = ref(false)
const dataForm = ref({
  refundAddrId: null,
  supplierId: null,
  shopId: null,
  supplierName: null,
  tel: null,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  contactName: null,
  contactTel: null,
  qqNumber: null,
  wxNumber: null,
  mail: null,
  fax: null,
  createTime: null,
  updateTime: null,
  status: 1
})
const provinceList = ref([]) // 省
const cityList = ref([]) // 市
const areaList = ref([]) // 区
const init = async supplierId => {
  dataForm.value.supplierId = supplierId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.value.provinceId = null
    dataForm.value.cityId = null
    dataForm.value.areaId = null
  })
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  if (dataForm.value.supplierId) {
    http({
      url: http.adornUrl('/supplier/supplier/info/' + dataForm.value.supplierId),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      if (data.provinceId) {
        listAreaByParentId(data.provinceId).then(({ data }) => {
          cityList.value = data
        })
      }
      if (data.cityId) {
        listAreaByParentId(data.cityId).then(({ data }) => {
          areaList.value = data
        })
      }
    })
  }
}
// 表单提交
const onSubmit = () => {
  onGetAreaName()
  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/supplier/supplier'),
        method: dataForm.value.supplierId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}

const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const onSelectProvince = val => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const onSelectCity = val => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const listAreaByParentId = pid => {
  const paramData = {}
  if (!pid) {
    paramData.level = 1
  } else {
    paramData.pid = pid
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
/**
 * 通过省市区id,得到省市区名称
 */
const onGetAreaName = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}
// 弹窗关闭的回调
const dataSelectRef = ref()
const onClosedDialog = () => {
  dataSelectRef.value?.blur()
}
defineExpose({ init })
</script>
